package com.bootdo.market.controller;

import com.bootdo.common.utils.AliyunOSSUtil;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.market.dao.DuplicateDao;
import com.bootdo.market.domain.ThirdSdkDO;
import com.bootdo.market.service.ThirdSdkService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author jinse
 * @email market@jinse.com
 * @date 2019-03-29 19:00:20
 */

@Controller
@RequestMapping("/market/thirdSdk")
public class ThirdSdkController {
    @Autowired
    private ThirdSdkService thirdSdkService;
    @Autowired
    private DuplicateDao duplicateDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping()
    @RequiresPermissions("market:thirdSdk:thirdSdk")
    String ThirdSdk(Integer sdkType, Model model) {
        model.addAttribute("sdktype", sdkType);
        return "market/thirdSdk/thirdSdk";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("market:thirdSdk:thirdSdk")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<ThirdSdkDO> thirdSdkList = thirdSdkService.list(query);
        int total = thirdSdkService.count(query);
        PageUtils pageUtils = new PageUtils(thirdSdkList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("market:thirdSdk:add")
    String add(Integer sdkType, Model model) {
        model.addAttribute("sdktype", sdkType);
        return "market/thirdSdk/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("market:thirdSdk:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        ThirdSdkDO thirdSdk = thirdSdkService.get(id);
        model.addAttribute("thirdSdk", thirdSdk);
        return "market/thirdSdk/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("market:thirdSdk:add")
    public R save(ThirdSdkDO thirdSdk) {
        if (thirdSdkService.save(thirdSdk) > 0) {
            thirdSdk.setThirdsdkid(thirdSdk.getSdkid() + thirdSdk.getId());
            thirdSdkService.update(thirdSdk);
            deleRedisChannelSdk(thirdSdk);
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("market:thirdSdk:edit")
    public R update(ThirdSdkDO thirdSdk) {
        thirdSdkService.update(thirdSdk);
        deleRedisChannelSdk(thirdSdk);

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("market:thirdSdk:remove")
    public R remove(ThirdSdkDO thirdSdk) {
        thirdSdkService.update(thirdSdk);
        deleRedisChannelSdk(thirdSdk);

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("market:thirdSdk:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] ids) {
        thirdSdkService.batchRemove(ids);
        return R.ok();
    }

    /**
     * apk|
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(HttpServletRequest request, MultipartFile file) throws Exception {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartHttpServletRequest.getFiles("file");
        String path = request.getSession().getServletContext().getRealPath("/");
        try {
            if (null != file) {
                String filename = file.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    File newFile = new File(path, filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    String uploadUrl = AliyunOSSUtil.uploadFile(newFile);
                    if (StringUtils.isNotBlank(uploadUrl)) {
                        return uploadUrl;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }
        return null;
    }

    /**
     * apk|
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/downFile")
    @ResponseBody
    public void downFile(HttpServletRequest request, HttpServletResponse response, String fileUrl) throws IOException {
        AliyunOSSUtil.downFile(request, response, fileUrl);
    }

    @RequestMapping(value = "/thirdSdkJudgingUniqueAdd", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public R thirdSdkJudgingUniqueAdd(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        Map<String, Object> aa = duplicateDao.thirdSdkJudgingUniqueAdd(params);
        if (aa == null) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @RequestMapping(value = "/thirdSdkJudgingUniqueEdit", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public R thirdSdkJudgingUniqueEdit(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        Map<String, Object> aa = duplicateDao.thirdSdkJudgingUniqueEdit(params);
        if (aa == null) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 删除Redis对应的key
     */
    void deleRedisChannelSdk(ThirdSdkDO thirdSdk) {
        if (thirdSdk.getIsoperate() == 0) {
            redisTemplate.delete("config_" + thirdSdk.getThirdsdkid());
        }
    }
}
